import React from "react";
import {hashHistory} from 'react-router';
import Relay from "react-relay";
import ReactKey from "../../util/ReactKey"

import {Invoice,OperLog} from './View_setEyeInfo';
import {Button,message,Input,Modal} from 'antd';
import Config from "../../util/Config"

import {EnBalanceDetail,ExamineEnBalance} from './mutation/ViewSetEyeInfo';

export default class A extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            Invoicelist:[
                {title:"发票张数",value:""}, {title:"快递公司",value:""},
                        {title:"快递单号",value:""}, {title:"发票附件",fileList:[]},
            ],  //发票信息

            operLogList:[],  // 操作日志
            ResultsViewInfo:{},  //结算信息
            vis:false,  //审核弹出框
            auditText:"",  //审核不通过value
            auditAlarm:false,  //审核不通过提示
            previewVisible:false, //预览图片是否隐藏
            previewImage:"",   //预览图片的src
        };

        // orderId;
        this.orderId = this.props.orderId && this.props.orderId;
        this.isResultsView = this.props.isResultsView && this.props.isResultsView;

        this.CanccelauditNoModal = this.CanccelauditNoModal.bind(this);
        this.auditNoChange = this.auditNoChange.bind(this);
        this.okAuditModal = this.okAuditModal.bind(this);
        this.perviewHandleCancel = this.perviewHandleCancel.bind(this);

        this.remitFileEye = this.remitFileEye.bind(this);
        this.remitFileEyeDown = this.remitFileEyeDown.bind(this);

    }

    componentWillMount(){
        const oid = this.props.location.state.orderId,
            isResultsView = this.props.location.state.isResultsView;

        oid ? this.orderId = oid : message.info("请按照规则进入页面");
        isResultsView && (this.isResultsView = isResultsView);
    }

    //sddsad
    componentDidMount(){
        Relay.Store.commitUpdate(
            new EnBalanceDetail({
                orderId:this.orderId
            }),{
                onFailure: () => {
                    message.error("网络请求失败")
                },
                onSuccess:(res)=>{
                    let data= null;
                    res ? data = res.enBalanceDetail.data : data = null;

                    if(!data || data.errorCode != "0"){  message.error("数据错误。请联系系统管理员"); return; }

                    data.errorCode == "500" && message.error("服务器错误，请联系系统管理员");

                    const r = JSON.parse(JSON.stringify(data.enterpriseBalance));

                    this.infoSuccess(r);
                }
            }
        )
    }

    //数据格式整理
    infoSuccess(r){
        let data = this.state.Invoicelist;
        //发票信息
        data[0].value = r.invoiceNum;   //发票张数
        data[1].value = r.expressName;   //快递公司
        data[2].value = r.expressSheet;  //快递单号
        data[3].fileList = JSON.parse(r.invoiceFileJson);  //发票附件

        //操作日志
        const l = r.balanceExamineLogList;
        l.map((item,index)=>{
          if(item.createTime) item.createTime = new Date(item.createTime).toLocaleString();
          return item;
        });

        //结算信息
        let re = this.state.ResultsViewInfo;
        re.balanceMoney = r.balanceMoney;
        re.repayMoney = r.repayMoney;
        re.remitFileJson = JSON.parse(r.remitFileJson);
        this.setState({Invoicelist:data, operLogList:JSON.parse(JSON.stringify(l)),ResultsViewInfo:re});

    }

    auditOk(alarm){
        const msUid = sessionStorage.getItem("msUid");
        const msUserName = sessionStorage.getItem("msUserName");

        if(alarm){
            Relay.Store.commitUpdate(
                new ExamineEnBalance({
                    orderId:this.orderId,
                    status:"3",
                    createId:msUid,
                    createBy:msUserName
                }),{
                    onFailure: () => {
                        message.error("网络请求失败")
                    },
                    onSuccess:(res)=>{
                        if(res.examineEnBalance.data.errorCode == "0"){
                            message.success("审核通过");
                            setTimeout(()=>{
                                hashHistory.push("/settlementcenter");
                            },2000)
                        }else{
                            message.info(res.examineEnBalance.data.value)
                        }
                    }
                }
            );
        }else{
            // message.info("审核不通过",3000);
            this.setState({vis:true})
        }
    }

    CanccelauditNoModal(){
        this.setState({
            vis:false,
            auditText:"",
            auditAlarm:false
        });
    }

    auditNoChange(e){this.setState({auditText:e.target.value　})}

    okAuditModal(){
        const  t = this.state.auditText,
                regu = "^[ ]+$",
                re = new RegExp(regu);

        const msUid = sessionStorage.getItem("msUid");
        const msUserName = sessionStorage.getItem("msUserName");

        if(t === "" || re.test(t)){
            this.setState({ auditAlarm:true });
        }else{
            Relay.Store.commitUpdate(
                new ExamineEnBalance({
                    orderId:this.orderId,
                    status:"5",
                    invoiceExamine:t,
                    createId:msUid,
                    createBy:msUserName
                }),{
                    onFailure: () => {
                        message.error("网络请求失败")
                    },
                    onSuccess:(res)=>{
                        if(res.examineEnBalance.data.errorCode == "0"){
                            this.setState({vis:false,auditText:"",auditAlarm:false});
                            message.info("审核不通过");
                            setTimeout(()=>{
                                hashHistory.push("/settlementcenter");
                            },2000)
                        }else{
                            message.error("操作失败"+ res.examineEnBalance.data.value);
                            this.setState({vis:false,auditText:"",auditAlarm:false});
                        }
                    }
                }
            );
        }
    }

    // 取消图片预览
    perviewHandleCancel(){ this.setState({
        previewVisible:false,
    }) }

    // 预览凭证
    remitFileEye(){
        const fs =this.state.ResultsViewInfo.remitFileJson;

        if(!fs || fs.length<= 0) { message.info("当前没有可预览对象"); return; }

        this.setState({previewVisible:true,previewImage:fs[0].url});
    }

    //下载凭证
    remitFileEyeDown() {
        const fs = this.state.ResultsViewInfo.remitFileJson;
        if(!fs){  message.info("当前没有保存内容");  return; }
        const f = fs[0];
        let a = document.createElement("a");
        a.href = `${Config.qiuniu+f.response.key}?attname=${f.name}`;
        a.setAttribute("download", "");
        a.click();
    }

    render() {
        const {Invoicelist,operLogList,auditText,auditAlarm,vis,previewVisible,previewImage,ResultsViewInfo} = this.state;
        let remitFileName = null, R = ResultsViewInfo.remitFileJson;

        if( R != undefined ){
            R.length > 0 ? remitFileName =  R[0].name : remitFileName = null
        }

        return(
            <div className="settlementCenterEye">
                <header className="settlementCenterEye_title">
                    <h2> 发票信息 </h2>
                </header>

                {/*发票信息*/}
                <div className="settlementCenterEye_Invoice_View" key="Invoice">
                    {
                        Invoicelist.map((item,index)=>{
                            return (
                                <div key={`infoItem${index}`} className="settlementCenterEye_infoItem">
                                    <strong > {item.title}：</strong>
                                    {
                                        item.title !== "发票附件" ?  <span >  {item.value}</span> :
                                            <span>
                                                {
                                                    item.fileList.map((item,index)=>
                                                        <a download href={`${Config.qiuniu+item.response.key}?attname=${item.name}`}>
                                                            {
                                                                item.name
                                                            }
                                                        </a>
                                                    )
                                                }
                                            </span>
                                    }
                                </div>
                            )
                        })
                    }
                </div>


                {
                    this.isResultsView == "4" && <div className="settlementCenterEye_ResultsView">
                        <h2> 结算信息 </h2>
                        <ul className="settlementCenterEye_Invoice_View">
                          <li><span> 结算金额：</span> {ResultsViewInfo.balanceMoney} </li>
                          <li><span> 还款金额：</span>{ResultsViewInfo.repayMoney}   </li>
                          <li><span style={{marginRight:20}}> 汇款凭证：{remitFileName}</span>
                              <Button type="primary" title="查看" size="small" style={{marginRight:10}} onClick={this.remitFileEye}> 查看</Button>
                              <Button type="primary" size="small" shape="circle" icon="download" title="下载" onClick={this.remitFileEyeDown}/>
                          </li>
                        </ul>
                    </div>
                }

                {
                    this.isResultsView == "2" &&  <footer>
                        <Button type="primary" onClick={(e)=>this.auditOk(true)} style={{marginRight:15}}> 审核通过 </Button>
                        <Button type="danger" onClick={(e)=>this.auditOk(false)}> 审核不通过 </Button>
                    </footer>
                }

                {/*操作日志*/}
                <div className="settlementCenterEye_operLog" key="settlementCenterEye_operLog">
                    <h2> 操作日志</h2>
                    <div className="settlementCenterEye_infoItem">

                        <div className="settlementCenterEye_OperLog">
                            <ul className="settlementCenterEye_Invoice_View" key="Invoice_view">
                                {
                                    operLogList.map((item,index)=>{
                                        return (
                                            <li key={index}>
                                                <span> {item.createTime} </span>
                                                <span> 操作人 ：{item.createBy} </span>
                                                <span> 操作类型 ：{item.examineDesc} </span>
                                                {
                                                    item.examineStatus == "5" &&
                                                        <div className="settlementCenterEye_OperLog_noDes">
                                                            <span>
                                                                    不通过理由 ：
                                                            </span>
                                                            <p>
                                                                       {item.failReason}
                                                            </p>
                                                        </div>
                                                }
                                            </li>
                                        )
                                    })
                                }
                            </ul>
                        </div>

                    </div>
                </div>


                <Modal
                    title="审核不通过"
                    onCancel={this.CanccelauditNoModal}
                    onOk={this.okAuditModal}
                    visible={vis}
                >
                    <Input type="textarea" rows={4} maxLength="100"
                           placeholder="填写不通过的理由，最多可输入100字"
                           value={auditText}
                           onChange={this.auditNoChange}
                           style={{boxSizing:"border-box"}}
                    />
                    <p className={auditAlarm ? "operLog_auditAlarm" : "hide"} >
                        请填写不通过的理由
                    </p>
                </Modal>

                {/*预览图片*/}
                <Modal  visible={previewVisible} footer={null} width={500} className="production_preview" onCancel={this.perviewHandleCancel}>
                    <img alt="example" style={{ width: '100%' }} src={previewImage} />
                </Modal>
            </div>
        )
    }
}